# 对评论文本内容的清洗
# param     text        评论文本
import datetime
import json
import random
import hashlib
import pafy
import chardet
import requests

from constant import VIDEO_PATH
from spider import config


def improve_format(text):
    return text.replace('\n', ' ')

def get_time_str():
    now = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    return now

def baidufanyi(q: str, from_type='auto', to='zh'):

    # print(chardet.detect(q))
    APPID = config.BAIDU_APPID
    SECRET = config.BAIDU_SECRET
    SALT = str(random.randint(0, 10000))
    SIGN = APPID + q + SALT + SECRET
    md5_sign = hashlib.md5(SIGN.encode()).hexdigest()

    response = requests.get(config.BAIDU_FY_API,
                 params={'q': q, 'from': from_type, 'to': to, 'appid': APPID, 'salt': SALT, 'sign': md5_sign})
    content = json.loads(response.content)
    # 判断错误
    if 'error_code' in content.keys():
        return 'error' + content['error_code']
    result = ''
    for i in content['trans_result']:
        result += i['dst']
    return result

def download_video(ytb_url,path=VIDEO_PATH):
    video = pafy.new(ytb_url)
    # except Exception as e:
    #     print(e)
    #     return False,None
    best = video.getbest()
    filename = "/YTB_V"+ get_time_str() + '.' + best.extension
    best.download(filepath=path+filename)
    return True,'media/material/video' + filename


if __name__ == '__main__':
    # t = baidufanyi("Her interaction with the granny is so cute. \nThat's probably my favorite part in all her videos. \U0001f970")
    # print(t)
    download_video('lRtedsK_6fs',path='../media/material/video')